﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using DevExpress.LocalizationCHS;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraEditors.Mask;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using JsalesModel;


namespace JSales.ModuleProduct
{
    public partial class ProductForm : Form
    {
        public ProductForm()
        {
            InitializeComponent();
            InitValidationRules();
        }

        private EditMode mode;

        private enum EditMode
        {
            Normal = 0,
            Edit = 1,
            Add = 2
        }

        private void ChangeEditMode(EditMode editMode)
        {
            switch (editMode)
            {
                case EditMode.Normal:
                    {
                        mode = EditMode.Normal;

                        barButtonItemAdd.Enabled = true;
                        barButtonItemEdit.Enabled = true;
                        barButtonItemDelete.Enabled = true;
                        barButtonItemSave.Enabled = false;
                        barButtonItemCancel.Enabled = false;

                        lookUpEditKind.Enabled = false;
                        tbGrammage.Enabled = false;
                        lookUpEditColor.Enabled = false;
                        lookUpEditTexture.Enabled = false;
                        tbProcess.Enabled = false;
                        tbDegree.Enabled = false;
                        tbLevel.Enabled = false;
                        tbWidth.Enabled = false;
                        tbLength.Enabled = false;
                        tbNum.Enabled = false;
                        tbProductName.Enabled = false;


                        gridView1.OptionsBehavior.Editable = false;
                        gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        //gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
                        dxValidationProvider1.RemoveControlError(lookUpEditKind);
                        dxValidationProvider1.RemoveControlError(lookUpEditColor);
                        dxValidationProvider1.RemoveControlError(lookUpEditTexture);
                        dxValidationProvider1.RemoveControlError(tbDegree);
                        dxValidationProvider1.RemoveControlError(tbGrammage);
                        dxValidationProvider1.RemoveControlError(tbLength);
                        dxValidationProvider1.RemoveControlError(tbLevel);
                        dxValidationProvider1.RemoveControlError(tbNum);
                        dxValidationProvider1.RemoveControlError(tbProcess);
                        dxValidationProvider1.RemoveControlError(tbProductName);
                        dxValidationProvider1.RemoveControlError(tbWidth);
                    }
                    break;
                case EditMode.Edit:
                    {
                        mode = EditMode.Edit;

                        barButtonItemAdd.Enabled = false;
                        barButtonItemEdit.Enabled = false;
                        barButtonItemDelete.Enabled = false;
                        barButtonItemSave.Enabled = true;
                        barButtonItemCancel.Enabled = true;

                        lookUpEditKind.Enabled = true;
                        tbGrammage.Enabled = true;
                        lookUpEditColor.Enabled = true;
                        lookUpEditTexture.Enabled = true;
                        tbProcess.Enabled = true;
                        tbDegree.Enabled = true;
                        tbLevel.Enabled = true;
                        tbWidth.Enabled = true;
                        tbLength.Enabled = true;
                        tbNum.Enabled = true;
                        tbProductName.Enabled = true;

                        gridView1.OptionsBehavior.Editable = false;
                        gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        //gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;

                        dxValidationProvider1.Validate();
                    }
                    break;
                case EditMode.Add:
                    {
                        mode = EditMode.Add;

                        barButtonItemAdd.Enabled = false;
                        barButtonItemEdit.Enabled = false;
                        barButtonItemDelete.Enabled = false;
                        barButtonItemSave.Enabled = true;
                        barButtonItemCancel.Enabled = true;

                        lookUpEditKind.Enabled = true;
                        tbGrammage.Enabled = true;
                        lookUpEditColor.Enabled = true;
                        lookUpEditTexture.Enabled = true;
                        tbProcess.Enabled = true;
                        tbDegree.Enabled = true;
                        tbLevel.Enabled = true;
                        tbWidth.Enabled = true;
                        tbLength.Enabled = true;
                        tbNum.Enabled = true;
                        tbProductName.Enabled = true;

                        gridView1.OptionsBehavior.Editable = false;
                        gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        //gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
                        dxValidationProvider1.Validate();
                    }
                    break;
            }
        }

        private BindingSource bindingSource = new BindingSource();

        private bool ProductisExist(string productid)
        {
            var dbContext = new JYEntities();
            IQueryable<TbProduct> products = from i in dbContext.TbProducts
                                             where i.ProductID == productid
                                             select i;
            if (products.Any())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void InitValidationRules()
        {
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = "值不能为空！";

            dxValidationProvider1.ValidationMode = ValidationMode.Auto;
            dxValidationProvider1.SetValidationRule(lookUpEditKind, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(lookUpEditColor, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(lookUpEditTexture, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbDegree, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbGrammage, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbLength, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbLevel, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbNum, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbProcess, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbProductName, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(tbWidth, notEmptyValidationRule);
        }

        private void ProductForm_Load(object sender, EventArgs e)
        {
            ChangeEditMode(EditMode.Normal);

            lookUpEditKind.Properties.DataSource = GlobalVar.GKinds;
            lookUpEditColor.Properties.DataSource = from i in GlobalVar.GColors where i.ISDELETED == false select i;
            lookUpEditTexture.Properties.DataSource = GlobalVar.GTextures;

            GlobalVar.SelectProduct();
            IQueryable<TbProduct> products = from i in GlobalVar.GProducts
                                             where i.Types == 2 && i.IsDeleted == false
                                             select i;

            //gridControl1.DataSource = products;

            if (products.Any())
            {
                bindingSource.DataSource = products;
                gridControl1.DataSource = bindingSource;

                lookUpEditColor.Properties.PopulateColumns();
                lookUpEditColor.Properties.Columns["COLORID"].Caption = "ID";
                lookUpEditColor.Properties.Columns["COLORNAME"].Caption = "颜色";
                lookUpEditColor.Properties.Columns["ISDELETED"].Visible = false;
                lookUpEditColor.Properties.Columns["ID"].Visible = false;
                lookUpEditColor.Properties.SearchMode = SearchMode.AutoFilter;

                lookUpEditKind.Properties.PopulateColumns();
                lookUpEditKind.Properties.Columns["KindID"].Caption = "ID";
                lookUpEditKind.Properties.Columns["KindName"].Caption = "纸类";
                lookUpEditKind.Properties.Columns["CreationDate"].Visible = false;
                lookUpEditKind.Properties.Columns["LastEditDate"].Visible = false;
                lookUpEditKind.Properties.Columns["ISDELETED"].Visible = false;
                lookUpEditKind.Properties.Columns["ID"].Visible = false;
                lookUpEditKind.Properties.SearchMode = SearchMode.AutoFilter;

                lookUpEditTexture.Properties.PopulateColumns();
                lookUpEditTexture.Properties.Columns["TEXTUREID"].Caption = "ID";
                lookUpEditTexture.Properties.Columns["TEXTURENAME"].Caption = "纹路";
                lookUpEditTexture.Properties.Columns["ISDELETED"].Visible = false;
                lookUpEditTexture.Properties.Columns["ID"].Visible = false;
                lookUpEditTexture.Properties.SearchMode = SearchMode.AutoFilter;

                repositoryItemLookUpEditKind.DataSource = GlobalVar.GKinds;
                repositoryItemLookUpEditColor.DataSource = GlobalVar.GColors;
                repositoryItemLookUpEditTexture.DataSource = GlobalVar.GTextures;
            }
        }

        private void gridView1_RowClick(object sender, RowClickEventArgs e)
        {
            gridView1.ClearSelection();

            int selectedHandle;
            selectedHandle = gridView1.GetSelectedRows()[0];
            lookUpEditKind.EditValue = gridView1.GetRowCellValue(selectedHandle, "Kindid").ToString();
            lookUpEditColor.EditValue = gridView1.GetRowCellValue(selectedHandle, "Color").ToString();
            lookUpEditTexture.EditValue = gridView1.GetRowCellValue(selectedHandle, "Texture").ToString();

            tbID.Text = gridView1.GetRowCellValue(selectedHandle, "ProductID").ToString();
            tbDegree.Text = gridView1.GetRowCellValue(selectedHandle, "Degree").ToString();
            tbGrammage.Text = gridView1.GetRowCellValue(selectedHandle, "Grammage").ToString();

            tbLevel.Text = gridView1.GetRowCellValue(selectedHandle, "Level").ToString();
            tbNum.Text = gridView1.GetRowCellValue(selectedHandle, "Num").ToString();
            tbProcess.Text = gridView1.GetRowCellValue(selectedHandle, "Process").ToString();
            tbLength.Text = gridView1.GetRowCellValue(selectedHandle, "Lengths").ToString();
            tbWidth.Text = gridView1.GetRowCellValue(selectedHandle, "Widths").ToString();
            tbProductName.Text = gridView1.GetRowCellValue(selectedHandle, "ProductName").ToString();
            //tbDegree.DataBindings.Clear();
            //tbDegree.DataBindings.Add("Text", bindingSource, "Degree");

            gridView1.RefreshData();
        }

        private void BarButtonAddItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeEditMode(EditMode.Add);
            mode = EditMode.Add;

            barButtonItemSave.Enabled = true;
            barButtonItemCancel.Enabled = true;
            barButtonItemEdit.Enabled = false;
            barButtonItemDelete.Enabled = false;
            barButtonItemAdd.Enabled = false;

            tbID.Text = null;
            lookUpEditKind.EditValue = null;
            tbGrammage.Text = null;
            lookUpEditColor.EditValue = null;
            lookUpEditTexture.EditValue = null;
            tbProcess.Text = null;
            tbDegree.Text = null;
            tbLevel.Text = null;
            tbWidth.Text = null;
            tbLength.Text = null;
            tbNum.Text = null;
            tbProductName.Text = null;
        }

        private void barButtonEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeEditMode(EditMode.Edit);
            gridView1.OptionsBehavior.Editable = true;
            gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            barButtonItemSave.Enabled = true;
        }

        private void barButtonCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridControl1.FocusedView.CloseEditor();
            ChangeEditMode(EditMode.Normal);
        }

        private void barButtonSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (mode == EditMode.Normal)
            {
                return;
            }
            else
            {
                var dbConText = new JYEntities();

                if (mode == EditMode.Add)
                {
                    string productid = lookUpEditKind.EditValue
                                       + "-" + tbGrammage.Text
                                       + "-" + lookUpEditColor.EditValue
                                       + "-" + lookUpEditTexture.EditValue
                                       + "-" + tbProcess.Text
                                       + "-" + tbDegree.Text
                                       + "-" + tbLevel.Text
                                       + "-" + tbLength.Text
                                       + "-" + tbNum.Text;
                    if (ProductisExist(productid))
                    {
                        MessageBox.Show("产品已存在！");
                    }
                    else
                    {
                        if (!lookUpEditKind.EditValue.Equals(null)
                            && !string.IsNullOrEmpty(tbGrammage.Text)
                            && !lookUpEditColor.EditValue.Equals(null)
                            && !lookUpEditTexture.EditValue.Equals(null)
                            && !string.IsNullOrEmpty(tbProcess.Text)
                            && !string.IsNullOrEmpty(tbDegree.Text)
                            && !string.IsNullOrEmpty(tbLevel.Text)
                            && !string.IsNullOrEmpty(tbWidth.Text)
                            && !string.IsNullOrEmpty(tbLength.Text)
                            && !string.IsNullOrEmpty(tbNum.Text)
                            && !string.IsNullOrEmpty(tbProductName.Text))
                        {
                            TbProduct product = new TbProduct();

                            product.Types = 2;
                            product.ProductID = productid;
                            product.Kindid = lookUpEditKind.EditValue.ToString();
                            product.Grammage = int.Parse(tbGrammage.Text);
                            product.Color = lookUpEditColor.EditValue.ToString();
                            product.Texture = lookUpEditTexture.EditValue.ToString();
                            product.Process = tbProcess.Text;
                            product.Degree = tbDegree.Text;
                            product.Level = tbLevel.Text[0];
                            product.Widths = double.Parse(tbWidth.Text);
                            product.Lengths = double.Parse(tbLength.Text);
                            product.Num = Int64.Parse(tbNum.Text);
                            product.ProductName = tbProductName.Text;
                            product.CreationDate = DateTime.Now;
                            product.LastEditDate = DateTime.Now;
                            product.IsDeleted = false;

                            dbConText.Add(product);
                            dbConText.SaveChanges();

                            ProductForm_Load(sender, e);
                        }
                        else
                        {
                            MessageBox.Show("数据请填写完整！");
                        }
                    }
                }
                else
                {
                    if (!lookUpEditKind.EditValue.Equals(null)
                        && !string.IsNullOrEmpty(tbGrammage.Text)
                        && !lookUpEditColor.EditValue.Equals(null)
                        && !lookUpEditTexture.EditValue.Equals(null)
                        && !string.IsNullOrEmpty(tbProcess.Text)
                        && !string.IsNullOrEmpty(tbDegree.Text)
                        && !string.IsNullOrEmpty(tbLevel.Text)
                        && !string.IsNullOrEmpty(tbWidth.Text)
                        && !string.IsNullOrEmpty(tbLength.Text)
                        && !string.IsNullOrEmpty(tbNum.Text)
                        && !string.IsNullOrEmpty(tbProductName.Text))
                    {
                        IQueryable<TbProduct> products = from i in dbConText.TbProducts
                                                         where i.ProductID == tbID.Text
                                                         select i;
                        if (products.Any())
                        {
                            TbProduct product = products.FirstOrDefault();
                            
                            product.Kindid = lookUpEditKind.EditValue.ToString();
                            product.Grammage = int.Parse(tbGrammage.Text);
                            product.Color = lookUpEditColor.EditValue.ToString();
                            product.Texture = lookUpEditTexture.EditValue.ToString();
                            product.Process = tbProcess.Text;
                            product.Degree = tbDegree.Text;
                            product.Level = tbLevel.Text[0];
                            product.Widths = double.Parse(tbWidth.Text);
                            product.Lengths = double.Parse(tbLength.Text);
                            product.Num = Int64.Parse(tbNum.Text);
                            product.ProductName = tbProductName.Text;
                            product.CreationDate = DateTime.Now;
                            product.LastEditDate = DateTime.Now;
                            product.IsDeleted = false;

                            dbConText.SaveChanges();

                            ProductForm_Load(sender, e);
                        }
                    }
                    else
                    {
                        MessageBox.Show("数据请填写完整！");
                    }
                }
            }
        }

        private void barButtonDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var dbConText = new JYEntities();
            IQueryable<TbProduct> products = from i in dbConText.TbProducts
                                             where i.ProductID == tbID.Text
                                             select i;
            if (products.Any())
            {
                TbProduct product = products.FirstOrDefault();
                product.IsDeleted = true;

                dbConText.SaveChanges();

                ProductForm_Load(sender, e);
            }
        }

        private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn IDColumn = view.Columns["ProductID"];
            if (view.GetRowCellValue(e.RowHandle, IDColumn).Equals("") ||
                view.GetRowCellValue(e.RowHandle, IDColumn).Equals(null))
            {
                e.Valid = false;
                view.SetColumnError(IDColumn, "产品ID不能为空！");
            }


            //else
            //{
            //    if (view.GetRowCellValue(e.RowHandle, IDColumn).ToString().Length > 3)
            //    {
            //        e.Valid = false;
            //        view.SetColumnError(IDColumn, "ID长度超过3位");
            //    }
            //}


            /*
            DataRowView focusedRow = (DataRowView)gridView1.GetFocusedRow();
            if (!focusedRow.IsNew) return;
            foreach (DataColumn column in focusedRow.DataView.Table.Columns)
            {
                e.Valid = !focusedRow.Row.IsNull(column);
                if (!e.Valid) return;
            }
            */
        }

        private void barButtonItemFind_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.FindPanelVisible = true;
        }
    }
}
